package com.atguigu.juc.date108;

/**
 * @Author: shenhao
 * @CreatTime: 2024/10/8 18:24
 * @Version: 1.0
 * 指令重排导致的错误数据
 */
public class ReSortSeqDemo {
    static int a;//加上volatile可以解决指令重排,禁止指令重排
    static int b;
    static int x;
    static int y;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        while (true) {
            i++; // 计数器
            a = b = x = y = 0;
            Thread thread1 = new Thread(() -> {
                a = 1;
                x = b;
            }, "t1");
            Thread thread2 = new Thread(() -> {
                b = 1;
                y = a;
            });
            thread1.start();
            thread2.start();
            thread1.join();//Waits for this thread to die.
            thread2.join();
            System.out.println("第" + i + "次打印:x=" + x + ",y=" + y);//x=0,y=1;顺序正常, y=1, x=0,线程2先运行,线程1后运行
            if (x == 0 && y == 0) {
                break;
            }
        }
    }
}
